<template>
  <div class="main-app">
    <el-form ref="form" :model="form" :rules="rules" label-width="600px" style="margin-top: 50px">
      <el-form-item label="序号:" prop="number" style="width: 60%">
        <el-input v-model="form.number" type="number" min="1" step="1" :disabled="isView" />
      </el-form-item>
      <el-form-item label="状态:" prop="status">
        <el-radio-group v-model="form.status" :disabled="isView">
          <el-radio v-for="(item, index) in options" :key="index" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="名称:" prop="content" style="width: 60%">
        <el-input v-model="form.content" clearable :disabled="isView" />
      </el-form-item>
      <!-- <el-form-item v-if="!isEdit" label="三证合一附件 (营业执照图片）:"> -->
      <el-form-item v-if="!isView" label="安全告知卡附件:">
        <el-upload action="" class="upload-demo" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                   :on-change="handleChangeLi" :auto-upload="false" :file-list="imageObjList"
        >
          <el-button size="small" type="primary">点击添加</el-button>
        </el-upload>
      </el-form-item>

      <el-form-item v-else label="安全告知卡附件:">
        <el-button type="primary" icon="el-icon-view" @click="
          ViewFile(
            '安全告知卡附件',
            `${form.pictureUrlList}`
          )
        "
        >
          点击查看</el-button>
      </el-form-item>
      <!-- <el-form-item label="安全告知卡附件:" style="width: 60%">
        <el-upload
          class="upload-demo"
          drag
          action=""
          :file-list="imageObjList"
          :on-remove="handleRemove"
          :on-change="handleChange"
          v-if="!isView"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip">上传PDF文件</div>
        </el-upload>
        <el-button
          v-else
          type="primary"
          icon="el-icon-view"
          @click="ViewFile('废物安全告知卡附件', `${form.securityCardUrlList}`)"
        >
          点击查看附件</el-button
        >
      </el-form-item> -->
    </el-form>
    <el-row style="margin-top: 40px; text-align: center">
      <el-form :inline="true" class="form-inline">
        <el-form-item>
          <el-button type="primary" :disabled="isView" @click="save">提交</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <div class="dialog_diy">
      <el-dialog :visible.sync="dialogVisible" width="70%" style="margin-top: -100px">
        <div slot="title" style="background: #1890ff; color: white">
          <div style="padding: 15px 20px">{{ picTitle }}</div>
        </div>
        <el-form ref="form" style="margin-top: 15px" :model="form">
          <div class="block">
            <el-carousel height="700px" style="text-align: center">
              <el-carousel-item v-for="item in urls" :key="item">
                <el-image style="height: 100%; width: 100%" fit="scale-down" :src="item" />
              </el-carousel-item>
            </el-carousel>
          </div>
          <el-row style="margin-top: 20px; text-align: center">
            <el-form :inline="true" class="form-inline">
              <el-form-item>
                <el-button @click="dialogVisible = false">返 回</el-button>
              </el-form-item>
            </el-form>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  EquipmentStatus
} from "../../../utils/resource";
import {
  save_New,
  updateImg,
  getById_New
} from "../../../api/system";
import {
  NewGUID
} from "../../../utils/index.js";
export default {
  data() {
    return {
      form: {
        content: "",
        status: "0",
        number: "",
        customOne: "",
      },
      // 上传图片用
      picFile: {
        code: '',
        file: [],
        type: "1",
        name: "",
        uid: "",
        isDel: "0" // 0表示新增，1表示删除
      },
      imageObjList: [],
      imageObjList_Del: [],
      fileList: [
        //   {
        //   name: 'food.jpeg',
        //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?food.jpeg'
        // },
      ],
      urls: [
        // "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg",
      ],
      picTitle: "",
      options: EquipmentStatus,
      rules: {
        number: [{
          required: true,
          message: "请输入序号",
          trigger: "blur",
        }],
        content: [{
          required: true,
          message: "请输入名称",
          trigger: "blur",
        }],
        status: [{
          required: true,
          message: "请选择状态",
          trigger: "change",
        }],
        enclosure: [{
          required: true,
          message: "请上传PDF文件",
          trigger: "change",
        }],
      },
      id: "",
      // pdf: "",
      dialogVisible: false,
    };
  },
  computed: {
    isView() {
      // return this.$route.name === "safetynotification-view";
      return this.$route.name === "废物安全告知卡详情";
    },
  },
  async created() {
    const {
      id
    } = this.$route.params;
    await this.getById_New(id);
    this.id = id;
  },
  methods: {
    async ViewFile(title, url) {
      this.picTitle = title;
      this.urls = [];
      this.urls = url.split(",");
      this.dialogVisible = true;
    },
    /**
       * 文件上传删除
       */
    handleRemove(file, fileList) {
      var obj = this.imageObjList.findIndex(item => {
        return item.uid === file.uid
      });
      if (obj >= 0) {
        if (this.imageObjList[obj].file) {
          this.imageObjList.splice(obj, 1);
        } else {
          this.imageObjList[obj].isDel = "1"; // 如果没有文件内容，说明此文件是从云上下载的
          this.imageObjList_Del.push(this.imageObjList[obj]);
          this.imageObjList.splice(obj, 1);
        }
      }
    },

    /**
       * 文件发生改变时
       */
    handleChangeLi(file, fileList) {
      var obj = {
        id: "",
        file: file.raw,
        type: "1", // 更新类型 (1: 营业执照图片，2: 道路运输许可证图片)
        name: file.name,
        uid: file.uid,
        isDel: "0"
      }
      this.imageObjList.push(obj);
    },
    handlePictureCardPreview(file) {

    },
    async getById_New(id) {
      const {
        data
      } = await getById_New(id);
      this.form.number = data.sort;
      this.form.content = data.value;
      this.form.customOne = data.customOne;
      this.form.status = data.status.toString();

      this.form.pictureUrlList = data.pictureUrlList;

      if (this.form.pictureUrlList) {
        this.imageObjList = [];
        this.form.pictureUrlList.forEach(item => {
          var List = item.split("/");
          var nameList = List[List.length - 1].split('?');
          var obj = {
            code: id,
            file: '',
            // type: "1", // 更新类型 (1: 营业执照图片，2: 道路运输许可证图片)
            name: nameList[1],
            uid: nameList[0].split(".")[0],
            url: item,
            isDel: "0"
          }
          this.imageObjList.push(obj);
        })
      }
    },
    save() {
      this.$refs["form"].validate(async(valid) => {
        if (valid) {
          this.$axios.startLoading();
          var thisID = "";
          const formData = new FormData();
          let message = "";
          var isAdd = "1";
          if (!this.id) {
            message = "废物安全告知卡新增成功";
            thisID = NewGUID();
            formData.append("code", thisID);

            isAdd = "1";
          } else {
            thisID = this.id;
            formData.append("code", this.id);
            isAdd = "0";
            message = "废物安全告知卡修改成功";
          }

          formData.append("type", "104");
          formData.append("ParentId", "0");
          formData.append("customOne", this.form.customOne);
          formData.append("value", this.form.content);
          formData.append("status", this.form.status);
          formData.append("sort", parseInt(this.form.number));
          formData.append("isAdd", isAdd);

          const {
            success,
            msg
          } = await save_New(formData);

          var imageFileList = [];
          this.imageObjList.forEach(item => {
            imageFileList.push(item);
          })
          this.imageObjList_Del.forEach(item => {
            imageFileList.push(item);
          })

          await this.updateImg(imageFileList, thisID);

          // 全局使用，使用和关闭加载页面
          this.$axios.closeLoading();
          if (success) {
            this.$notify({
              title: "成功",
              message: message,
              type: "success",
              duration: 3000,
            });
            this.$router.push("/system/safetynotification");
          } else {
            this.$notify.error({
              title: "失败",
              message: msg,
              duration: 3000,
            });
          }
        }
      });
    },
    async updateImg(imageFileList, guid) {
      for (let i = 0; i < imageFileList.length; i++) {
        const imageFormData = new FormData();
        imageFormData.append('code', guid);
        imageFormData.append('type', imageFileList[i].type);
        imageFormData.append('file', imageFileList[i].file);

        imageFormData.append('name', imageFileList[i].name);
        imageFormData.append('uid', imageFileList[i].uid);
        imageFormData.append('isDel', imageFileList[i].isDel);
        console.log(imageFileList[i]);
        await updateImg(imageFormData);
      }
    },

    cancel() {
      this.$router.push("/system/safetynotification");
    },
  },
};
</script>
